package com.bytedance.gateway.filter;

import com.bytedance.gateway.commoin.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@Order(1)
@Slf4j
public class AuthorizeFilter implements GlobalFilter {

    @Autowired
    private RedisTemplate redisTemplate;


    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    private String[] excludePath = new String[]{
            "/douyin/user/register/**",
            "/douyin/user/login/**",
            "/douyin/feed/**",
            "/douyin/publish/action/**"
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //对请求路径进行判断
        String path = exchange.getRequest().getPath().value();
        boolean checked = check(path, excludePath);
        if (checked) {
            return chain.filter(exchange);
        }
        //如果不是，则进一步判断携带的token有效性
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 2.获取token参数
        String token = params.getFirst("token");
        if (token == null || "".equals(token)) {
            token = "防止token为空校验出bug！";
        }
        // 3.校验
        Boolean checkToken = JwtUtil.checkToken(token);
        JSONObject jsonObject = new JSONObject();

        if (checkToken) {
            // 对token中的userId进行判断
            Long userId = JwtUtil.parseToken(token);
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Long userId1 = (Long) valueOperations.get(userId);
            log.error("从redis获取userId1:" + userId1);
            if (userId1 != null) {
                String ip = exchange.getRequest().getRemoteAddress().getHostName();
                ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders -> {
                    httpHeaders.add("userfrom", ip);
                    httpHeaders.add("userid", String.valueOf(userId1));
                }).build();
                exchange.mutate().request(serverHttpRequest);
                // 发送消息
                log.info(ip);
                log.info(path);
                return chain.filter(exchange);
            }
        }
        // token无效，禁止访问，设置状态码
        jsonObject.put("status_code", 1);
        jsonObject.put("status_msg", "未登录以及token过期不可进行该操作嗷！");
        //把json对象转换成字节数组
        byte[] bits = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
        //把字节数据转换成一个DataBuffer
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        return response.writeWith(Mono.just(buffer));
    }

    public boolean check(String requestURI, String[] excludePath) {
        for (String url : excludePath) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
